package com.dtwave.wechat.service.provider.core.wx;

import com.dtwave.wechat.service.provider.web.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Auther: liuwenxiang
 * @Date: 2019/2/23 15:26
 * @Description:
 */
@Component
public class WeiXinMakeToken extends BaseController implements InitializingBean {

    private static Logger log = LoggerFactory.getLogger(WeiXinMakeToken.class);

    @Autowired
    WeiXinProperties weiXinProperties;

    public static AccessToken accessToken_txl = null;

    public static AccessToken accessToken_tztb = null;

    public static AccessToken accessToken_xxsb = null;

    @Override
    public void afterPropertiesSet() throws Exception {

        POOL.submit(()->{
            while(true){

                try {
                    accessToken_txl =  WeiXinMethodUtil.getAccessToken(weiXinProperties.getCropid(), weiXinProperties.getAppsecret_txl(),1);
                    accessToken_tztb =  WeiXinMethodUtil.getAccessToken(weiXinProperties.getCropid(), weiXinProperties.getAppsecret_tztb(),1);
                    accessToken_xxsb =  WeiXinMethodUtil.getAccessToken(weiXinProperties.getCropid(), weiXinProperties.getAppsecret_xxsb(),1);

                    if (null != accessToken_txl||null != accessToken_tztb||null != accessToken_xxsb) {
                        log.info("获取通信录access_token成功，有效时长{}秒 token:{}", accessToken_txl.getExpiresIn(), accessToken_txl.getToken());
                        log.info("获取通知通报access_token成功，有效时长{}秒 token:{}", accessToken_tztb.getExpiresIn(), accessToken_tztb.getToken());
                        log.info("获取信息上报access_token成功，有效时长{}秒 token:{}", accessToken_xxsb.getExpiresIn(), accessToken_xxsb.getToken());
                        // 休眠7000秒
                        Thread.sleep((accessToken_txl.getExpiresIn() - 200) * 1000);
                    } else {
                        // 如果access_token为null，60秒后再获取
                        Thread.sleep(60 * 1000);
                    }
                } catch (InterruptedException e) {
                    try {
                        Thread.sleep(60 * 1000);
                    } catch (InterruptedException e1) {
                        log.error("{}", e1);
                    }
                    log.error("{}", e);
                }

            }
        });


    }




}
